import {
  getSpikeProduct,
  getRecommendProduct,
  getCheaperProduct,
  getCategory,
  getDetail,
  getOptionPrice,
  addProduct,
  getIndustryServer,
  getRecommendByOrgService,
  getProductTotalNumService,
  getSecondIndustryServer,
  freightServer,
  topProductListServer,
  productGroupsServer,
  productGroupListServer,
  appProductListServer,
  activityProductListServer,
} from '@/services/productList';
import Taro from '@tarojs/taro';
import utils from '@/utils/index';
import { getDefaultOptions } from '../dataTransfer/product';
import { dealPayloadParams } from './commonFunc';

export default {
  namespace: 'productList',
  state: {
    // 获取活动商品分页列表
    activityProductList: undefined,
    activityProductListParams: {},
    activityProductListPagination: {},
    activityProductListFinished: false,

    // 获取配置商品
    appProductList: [],
    appProductListParams: {},
    appProductListPagination: {},
    appProductListFinished: false,

    // 商城分组商品列表
    productGroupList: [],
    productGroupListParams: {},
    productGroupListPagination: {},
    productGroupListFinished: false,

    // 商城商品分组列表
    productGroups: [],

    // 商品详情配送费
    freight: undefined,

    // 购物车 商品数量
    carNum: undefined,

    cheaperProductList: [],

    shopProductParams: {},
    shopProductList: [],
    shopProductPagination: {},
    shopProductListFinished: false,

    shopIndustryProductList: {},
    shopIndustryProductPagination: [],
    shopIndustryProductParams: {},
    shopIndustryProductListFinished: false,

    cheaperAllParams: {},
    cheaperAllList: [],
    cheaperAllPagination: {},
    cheaperAllFinished: false,

    recProductParams: {},
    recProductList: [],
    recProductFinished: false,

    curProduct: {},
    productDetail: {},
    industry: [],

    recShopProductParams: {},
    recShopProductList: [],
    recShopProductPagination: {},
    recShopProductFinished: false,

    productNumInCart: null,

    secondIndustry: [],
  },
  effects: {
    // 获取活动商品分页列表
    *fetchActivityProductList({ payload }, { select, call, put }) {
      const params = yield select(({ productList }) => productList.activityProductListParams);
      const curIsFinished = yield select(
        ({ productList }) => productList.activityProductListFinished,
      );

      const isAlreadyFinished = dealPayloadParams(payload, params, curIsFinished);
      if (isAlreadyFinished) {
        return;
      }

      // if (payload.page === 1) {
      //   yield put({
      //     type: 'setActivityProductList',
      //     payload: {
      //       activityProductList: undefined,
      //       activityProductListFinished: false,
      //     },
      //   });
      // }

      const res = yield call(activityProductListServer, payload);
      if (res.code !== '1') {
        Taro.showToast({
          title: res.message,
          duration: 1000,
          icon: 'none',
        });
        return Promise.reject();
      }

      const { list, pagination } = res.content;
      let dataList = [];
      if (payload.page != 1) {
        const oldList = yield select(({ productList }) => productList.activityProductList);
        dataList = [...oldList, ...list];
      } else {
        dataList = [...list];
      }
      let isFinished = false;
      if (list.length < payload.pageSize) {
        isFinished = true;
      }
      yield put({
        type: 'setActivityProductList',
        payload: {
          activityProductList: dataList,
          activityProductListPagination: { ...pagination },
          activityProductListParams: { ...payload },
          activityProductListFinished: isFinished,
        },
      });

      return dataList;
    },

    // 获取配置商品, 不分页!
    *fetchAppProductInfo({ payload }, { call }) {
      const res = yield call(appProductListServer, payload);
      if (res.code !== '1') {
        Taro.showToast({
          title: res.message,
          duration: 1000,
          icon: 'none',
        });
        return Promise.reject();
      }

      return res.content;
    },

    // 获取配置商品
    *fetchAppProductList({ payload }, { select, call, put }) {
      const params = yield select(({ productList }) => productList.appProductListParams);
      const curIsFinished = yield select(({ productList }) => productList.appProductListFinished);

      const isAlreadyFinished = dealPayloadParams(payload, params, curIsFinished);
      if (isAlreadyFinished) {
        return;
      }

      if (payload.page === 1) {
        yield put({
          type: 'setAppProductList',
          payload: {
            appProductList: [],
            appProductListFinished: false,
          },
        });
      }

      const res = yield call(appProductListServer, payload);
      if (res.code !== '1') {
        Taro.showToast({
          title: res.message,
          duration: 1000,
          icon: 'none',
        });
        return Promise.reject();
      }

      const { list, pagination } = res.content;
      let dataList = [];
      if (payload.page != 1) {
        const oldList = yield select(({ productList }) => productList.appProductList);
        dataList = [...oldList, ...list];
      } else {
        dataList = [...list];
      }
      let isFinished = false;
      if (list.length < payload.pageSize) {
        isFinished = true;
      }
      yield put({
        type: 'setAppProductList',
        payload: {
          appProductList: dataList,
          appProductListPagination: { ...pagination },
          appProductListParams: { ...payload },
          appProductListFinished: isFinished,
        },
      });
    },

    // 商城分组商品列表
    *fetchProductGroupList({ payload }, { select, call, put }) {
      const params = yield select(({ productList }) => productList.productGroupListParams);
      const curIsFinished = yield select(({ productList }) => productList.productGroupListFinished);

      const isAlreadyFinished = dealPayloadParams(payload, params, curIsFinished);
      if (isAlreadyFinished) {
        return;
      }

      if (payload.page === 1) {
        yield put({
          type: 'setProductGroupList',
          payload: {
            productGroupList: [],
            productGroupListFinished: false,
          },
        });
      }

      const res = yield call(productGroupListServer, payload);
      if (res.code !== '1') {
        Taro.showToast({
          title: res.message,
          duration: 1000,
          icon: 'none',
        });
        return Promise.reject();
      }

      const { list, pagination } = res.content;
      let dataList = [];
      if (payload.page != 1) {
        const oldList = yield select(({ productList }) => productList.productGroupList);
        dataList = [...oldList, ...list];
      } else {
        dataList = [...list];
      }
      let isFinished = false;
      if (list.length < payload.pageSize) {
        isFinished = true;
      }
      yield put({
        type: 'setProductGroupList',
        payload: {
          productGroupList: dataList,
          productGroupListPagination: { ...pagination },
          productGroupListParams: { ...payload },
          productGroupListFinished: isFinished,
        },
      });
    },
    // 商城商品分组列表
    *fetchProductGroups({ payload }, { call, put }) {
      yield put({
        type: 'setProductGroups',
        payload: [],
      });

      const res = yield call(productGroupsServer, payload);
      if (res.code !== '1') {
        Taro.showToast({
          title: res.message,
          duration: 1000,
          icon: 'none',
        });
        return Promise.reject();
      }

      yield put({
        type: 'setProductGroups',
        payload: res.content,
      });

      return res.content;
    },

    // 商品详情配送费
    *getFreight({ payload }, { call, put }) {
      yield put({
        type: 'setFreight',
        payload: undefined,
      });

      const res = yield call(freightServer, payload);
      if (res.code !== '1') {
        Taro.showToast({
          title: res.message,
          duration: 1000,
          icon: 'none',
        });
        return Promise.reject();
      }

      yield put({
        type: 'setFreight',
        payload: res.content,
      });

      return res.content;
    },

    *getSpikeProduct({}, { call }) {
      const res = yield call(getSpikeProduct);
      const { code, content } = res;
      if (code === '1') {
        return content;
      } else {
      }
    },
    *getRecommendProduct({ payload }, { call }) {
      const res = yield call(getRecommendProduct, payload);
      if (res.code == 1) {
        return res.content;
      } else {
      }
    },
    *getCategory({}, { call }) {
      const res = yield call(getCategory);
      if (res.code == 1) {
        return res.content;
      } else {
      }
    },
    *getIndustry({}, { call, put }) {
      const res = yield call(getIndustryServer);
      if (res.code == 1) {
        let list = [];
        if (res.content.length > 0) {
          list = res.content.map((item) => {
            item.title = item.name ?? item.title;
            return item;
          });
        }

        list.unshift({
          title: '全部',
        });
        yield put({
          type: 'setIndustry',
          payload: { list },
        });
      } else {
        Taro.showToast({
          title: '获取行业分类失败',
          duration: 1000,
          icon: 'none',
        });
      }
    },
    *getSecondIndustry({ payload }, { call, put }) {
      const res = yield call(getSecondIndustryServer, payload);
      if (res.code == '1') {
        let list = [...res.content];

        list.unshift({
          id: 0,
          title: '全部',
        });
        yield put({
          type: 'setSecondIndustry',
          payload: { list },
        });
      } else {
        Taro.showToast({
          title: '获取二级行业分类失败',
          duration: 1000,
          icon: 'none',
        });
      }
    },
    *getRecommendProductByIndustry({ payload }, { select, call, put }) {
      const params = yield select(({ productList }) => productList.recProductParams);
      const curIsFinished = yield select(({ productList }) => productList.recProductFinished);

      const isAlreadyFinished = dealPayloadParams(payload, params, curIsFinished);
      if (isAlreadyFinished) {
        return;
      }

      const res = yield call(topProductListServer, payload);
      if (res.code == 1) {
        const list = res.content || [];
        let dataList = [];
        if (payload.page != 1) {
          const curRecProductList = yield select(({ productList }) => productList.recProductList);
          dataList = [...curRecProductList, ...list];
        } else {
          dataList = [...list];
        }
        let isFinished = false;
        if (list.length < payload.pageSize) {
          isFinished = true;
        }
        yield put({
          type: 'setRecProductList',
          payload: {
            recProductList: dataList,
            recProductParams: { ...payload },
            recProductFinished: isFinished,
          },
        });
      } else {
        Taro.showToast({
          title: '获取行业商品失败',
          duration: 1000,
          icon: 'none',
        });
      }
    },
    *getDetail({ payload }, { select, call, put }) {
      const curProduct = yield select(({ productList }) => productList.curProduct);
      const res = yield call(getDetail, payload);
      if (res.code == 1) {
        let productData = res.content;
        let dOptions = JSON.parse(productData.options);
        if (productData.bodyHtml == 'null') {
          productData.bodyHtml = '';
        }
        productData.options = dOptions;
        const { isNeedChoice, defaultSel, isWithOption, isWithOptionSold, stockPath, optionList } =
          getDefaultOptions(productData, curProduct);

        console.log('==================', {
          isNeedChoice,
          defaultSel,
          isWithOption,
          isWithOptionSold,
          stockPath,
          optionList,
        });

        productData.defaultSel = defaultSel;
        productData.isNeedChoice = isNeedChoice;
        productData.isWithOption = isWithOption;
        productData.isWithOptionSold = isWithOptionSold;
        productData.stockPath = stockPath;
        productData.optionList = optionList;

        productData.supportKuaidi = false;
        productData.supportWaimai = false;
        productData.supportZiti = false;
        if (productData.distributionWay && productData.distributionWay.length > 0) {
          productData.distributionWay.map((sp) => {
            if (sp == 1) {
              productData.supportKuaidi = true;
            } else if (sp == 2) {
              productData.supportWaimai = true;
            } else if (sp == 3) {
              productData.supportZiti = true;
            }
          });
        }
        yield put({
          type: 'setProductDetail',
          payload: { ...productData },
        });
      } else {
        Taro.showToast({
          title: '获取商品详情失败',
          duration: 1000,
          icon: 'none',
        });
      }
    },
    *getOptionPrice({ payload }, { call }) {
      const res = yield call(getOptionPrice, payload);
      if (res.code == 1) {
        return res.content;
      } else {
        return res
      }
    },
    *addProduct({ payload }, { call, put, take }) {
      const res = yield call(addProduct, payload);

      if (res.code === '1') {
        // 重新获取购物车数量
        yield put({ type: 'getCarNum', payload: {} });
        yield take('getCarNum/@@end');
      }

      return res;
    },
    *getCheaperProductList({ payload }, { call, put }) {
      const res = yield call(getCheaperProduct, payload);
      if (res.code == 1) {
        const { list } = res.content;
        yield put({
          type: 'setCheaperProductList',
          payload: {
            cheaperProductList: [...list],
          },
        });
      } else {
        Taro.showToast({
          title: '获取省钱专区商品失败',
          duration: 1000,
          icon: 'none',
        });
      }
    },

    *getCheaperAllList({ payload }, { select, call, put }) {
      const params = yield select(({ productList }) => productList.cheaperAllParams);
      const curIsFinished = yield select(({ productList }) => productList.cheaperAllListFinished);

      const isAlreadyFinished = dealPayloadParams(payload, params, curIsFinished);
      if (isAlreadyFinished) {
        return;
      }

      const res = yield call(getCheaperProduct, payload);
      if (res.code == 1) {
        const { list, pagination } = res.content;
        let dataList = [];
        if (payload.page != 1) {
          const curCheaperAllList = yield select(({ productList }) => productList.cheaperAllList);
          dataList = [...curCheaperAllList, ...list];
        } else {
          dataList = [...list];
        }
        let isFinished = false;
        if (dataList.length >= pagination.totalCount) {
          isFinished = true;
        }
        yield put({
          type: 'setCheaperAllList',
          payload: {
            cheaperAllList: dataList,
            cheaperAllPagination: { ...pagination },
            cheaperAllParams: { ...payload },
            cheaperAllFinished: isFinished,
          },
        });
      } else {
        Taro.showToast({
          title: '获取省钱专区商品失败',
          duration: 1000,
          icon: 'none',
        });
      }
    },

    *getShopProductList({ payload }, { select, call, put }) {
      const params = yield select(({ productList }) => productList.shopProductParams);
      const curIsFinished = yield select(({ productList }) => productList.shopProductListFinished);

      const isAlreadyFinished = dealPayloadParams(payload, params, curIsFinished);
      if (isAlreadyFinished) {
        return;
      }

      const res = yield call(topProductListServer, payload);
      if (res.code == 1) {
        const list = res.content || [];
        let dataList = [];
        if (payload.page != 1) {
          const curShopProductList = yield select(({ productList }) => productList.shopProductList);
          dataList = [...curShopProductList, ...list];
        } else {
          dataList = [...list];
        }
        let isFinished = false;
        if (list.length < payload.pageSize) {
          isFinished = true;
        }
        yield put({
          type: 'setShopProductList',
          payload: {
            shopProductList: dataList,
            shopProductParams: { ...payload },
            shopProductListFinished: isFinished,
          },
        });
      } else {
        Taro.showToast({
          title: '获取商品失败',
          duration: 1000,
          icon: 'none',
        });
      }
    },

    *getShopIndustryProductList({ payload }, { select, call, put }) {
      const params = yield select(({ productList }) => productList.shopIndustryProductParams);
      const curIsFinished = yield select(
        ({ productList }) => productList.shopIndustryProductListFinished,
      );

      const isAlreadyFinished = dealPayloadParams(payload, params, curIsFinished);
      if (isAlreadyFinished) {
        return;
      }

      const res = yield call(getRecommendProduct, payload);
      if (res.code == 1) {
        const { list } = res.content;
        let dataList = [];
        if (payload.page != 1) {
          const curShopProductList = yield select(
            ({ productList }) => productList.shopIndustryProductList,
          );
          dataList = [...curShopProductList, ...list];
        } else {
          dataList = [...list];
        }
        let isFinished = false;
        if (list.length < payload.pageSize) {
          isFinished = true;
        }
        yield put({
          type: 'setShopIndustryProductList',
          payload: {
            shopIndustryProductList: dataList,
            shopIndustryProductParams: { ...payload },
            shopIndustryProductListFinished: isFinished,
          },
        });
      } else {
        Taro.showToast({
          title: '获取分类商品失败',
          duration: 1000,
          icon: 'none',
        });
      }
    },

    *getRecommendByOrg({ payload }, { select, call, put }) {
      const params = yield select(({ productList }) => productList.recShopProductParams);
      const curIsFinished = yield select(({ productList }) => productList.recShopProductFinished);

      const isAlreadyFinished = dealPayloadParams(payload, params, curIsFinished);
      if (isAlreadyFinished) {
        return;
      }
      if (payload.page == 1) {
        yield put({
          type: 'setRecShopProductList',
          payload: {
            recShopProductList: [],
          },
        });
      }

      const res = yield call(getRecommendByOrgService, payload);
      if (res.code == 1) {
        const { list, pagination } = res.content;
        let dataList = [];
        if (payload.page != 1) {
          const curRecProductList = yield select(
            ({ productList }) => productList.recShopProductList,
          );
          dataList = [...curRecProductList, ...list];
        } else {
          dataList = [...list];
        }
        let isFinished = false;
        if (dataList.length >= pagination.totalCount) {
          isFinished = true;
        }
        yield put({
          type: 'setRecShopProductList',
          payload: {
            recShopProductList: dataList,
            recShopProductPagination: { ...pagination },
            recShopProductParams: { ...payload },
            recShopProductFinished: isFinished,
          },
        });
      } else {
        Taro.showToast({
          title: '获取商品失败',
          duration: 1000,
          icon: 'none',
        });
      }
    },

    *getProductTotalNum({ payload }, { call, put }) {
      const res = yield call(getProductTotalNumService, payload);
      if (res.code == 1) {
        const { num } = res.content;
        yield put({
          type: 'setProductTotalNum',
          payload: {
            productNumInCart: num,
          },
        });
      } else {
        Taro.showToast({
          title: '获取购物车商品数量失败',
          duration: 1000,
          icon: 'none',
        });
      }
    },

    *getCarNum({ payload }, { call, put }) {
      let token = utils.getToken();

      let result = {
        carNum: undefined,
      };

      if (token) {
        const res = yield call(getProductTotalNumService, payload, true);
        const content = res?.data?.content ?? {};

        if (content && content.carNum) {
          result = {
            carNum: content.carNum,
          };
        }
      }

      yield put({
        type: 'setCarNum',
        payload: result,
      });
    },
  },
  reducers: {
    // 获取活动商品分页列表
    setActivityProductList(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },

    // 获取配置商品
    setAppProductList(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },

    // 商城分组商品列表
    setProductGroupList(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },

    // 商城商品分组列表
    setProductGroups(state, { payload }) {
      return {
        ...state,
        productGroups: payload,
      };
    },

    // 商品详情配送费
    setFreight(state, { payload }) {
      return {
        ...state,
        freight: payload,
      };
    },

    setCheaperProductList(state, { payload }) {
      const { cheaperProductList } = payload;
      return {
        ...state,
        cheaperProductList,
      };
    },
    setCheaperAllList(state, { payload }) {
      const { cheaperAllList, cheaperAllPagination, cheaperAllParams, cheaperAllFinished } =
        payload;
      return {
        ...state,
        cheaperAllList,
        cheaperAllPagination,
        cheaperAllParams,
        cheaperAllFinished,
      };
    },
    setRecProductList(state, { payload }) {
      const { recProductList, recProductParams, recProductFinished } = payload;
      return {
        ...state,
        recProductList,
        recProductParams,
        recProductFinished,
      };
    },
    setShopProductList(state, { payload }) {
      const { shopProductList, shopProductParams, shopProductListFinished } = payload;
      return {
        ...state,
        shopProductList,
        shopProductParams,
        shopProductListFinished,
      };
    },
    setShopIndustryProductList(state, { payload }) {
      const {
        shopIndustryProductList,
        shopIndustryProductParams,
        shopIndustryProductListFinished,
      } = payload;
      return {
        ...state,
        shopIndustryProductList,
        shopIndustryProductParams,
        shopIndustryProductListFinished,
      };
    },
    clearShopIndustryProductList(state, {}) {
      return {
        ...state,
        shopIndustryProductList: [],
        shopIndustryProductParams: {},
        shopIndustryProductListFinished: false,
      };
    },
    setCurProduct(state, { payload }) {
      return {
        ...state,
        curProduct: { ...payload },
      };
    },
    setProductDetail(state, { payload }) {
      return {
        ...state,
        productDetail: { ...payload },
      };
    },
    setIndustry(state, { payload }) {
      const { list } = payload;
      return {
        ...state,
        industry: [...list],
      };
    },
    setSecondIndustry(state, { payload }) {
      const { list } = payload;
      return {
        ...state,
        secondIndustry: [...list],
      };
    },
    setRecShopProductList(state, { payload }) {
      const {
        recShopProductList,
        recShopProductPagination,
        recShopProductParams,
        recShopProductFinished,
      } = payload;
      return {
        ...state,
        recShopProductList,
        recShopProductPagination,
        recShopProductParams,
        recShopProductFinished,
      };
    },
    setProductTotalNum(state, { payload }) {
      const { productNumInCart } = payload;
      return {
        ...state,
        productNumInCart,
      };
    },
    setCarNum(state, { payload }) {
      const { carNum } = payload;
      return {
        ...state,
        carNum,
      };
    },
  },
};
